package com.java110.mall.chain.cmd.chainProduct;

import com.alibaba.fastjson.JSONObject;
import com.java110.mall.chain.supplier.ISupplierAdapter;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.dto.chain.ChainSupplierDto;
import com.java110.intf.chain.IChainCoreInnerServiceSMO;
import com.java110.intf.chain.IChainSupplierV1InnerServiceSMO;
import com.java110.utils.exception.CmdException;
import com.java110.utils.factory.ApplicationContextFactory;
import com.java110.utils.util.Assert;
import com.java110.utils.util.StringUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.List;

@Java110Cmd(serviceCode = "chainProduct.callBackChainProduct")
public class CallBackChainProductCmd extends Cmd {

    @Autowired
    private IChainCoreInnerServiceSMO chainCoreInnerServiceSMOImpl;

    @Autowired
    private IChainSupplierV1InnerServiceSMO chainSupplierV1InnerServiceSMOImpl;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {
        Assert.hasKeyAndValue(reqJson, "csId", "未包含供应链ID");
    }

    @Override
    public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {


        ChainSupplierDto tmpChainSupplierDto = getAdapterName(reqJson.getString("csId"));
        if (tmpChainSupplierDto == null || StringUtil.isEmpty(tmpChainSupplierDto.getBeanName())) {
            throw new IllegalArgumentException("供应商错误");
        }
        ISupplierAdapter supplierAdapter = ApplicationContextFactory.getBean(tmpChainSupplierDto.getBeanName(), ISupplierAdapter.class);
        if (supplierAdapter == null) {
            throw new IllegalArgumentException("供应商错误");
        }
        ResultVo resultVo = supplierAdapter.callBackChainProduct(reqJson.getString("param"),tmpChainSupplierDto);

        cmdDataFlowContext.setResponseEntity(new ResponseEntity(resultVo.toString(), HttpStatus.OK));
    }


    /**
     * 查询 适配器名称
     *
     * @param csId
     * @return
     */
    public ChainSupplierDto getAdapterName(String csId) {

        ChainSupplierDto chainSupplierDto = new ChainSupplierDto();
        chainSupplierDto.setCsId(csId);
        List<ChainSupplierDto> chainSupplierDtos = chainSupplierV1InnerServiceSMOImpl.queryChainSuppliers(chainSupplierDto);
        if (chainSupplierDtos == null || chainSupplierDtos.size() < 1) {
            return null;
        }
        return chainSupplierDtos.get(0);
    }
}
